<?php

namespace Crm\Controller;

/**
 * 客户控制器
 * 
 * @author SoChishun <14507247@qq.com>
 * @since 1.0.0 <2015-4-2> SoChishun Added.
 */
class CustomerController extends AppbaseController {

    /**
     * 检测用户访问权限
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function assert_upr($rule = '') {
        //$upr['客户管理'] = equal_permission('KH_KHGL', $uid);
        $upr = array(
            'customer_list' => true,
            'customer_edit' => true,
        );

        $this->user_permission_rules = $upr;
        if ($rule && (!array_key_exists($rule, $upr) || !$upr[$rule])) {
            die('您没有访问权限!');
        }
    }

    /**
     * 获取customer_list查询表单数据
     * @return array 包含search和where数组
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    function customer_list_search() {
        $search = I('get.');
        if ($search['keyword']) {
            $where['name'] = array('like', '%' . $search['keyword'] . '%');
        }
        if ($search['tel']) {
            $where['telphone'] = array('like', '%' . $search['tel'] . '%');
        }
        if ($search['personalName']) {
            $where['personalName'] = array('like', '%' . $search['personalName'] . '%');
        }
        if ($search['userName']) {
            $where['userName'] = $search['userName'];
        }
        if ($search['agentPersonalName']) {
            $where['agentPersonalName'] = $search['agentPersonalName'];
        }
        if ($search['sn']) {
            $where['serialNo'] = $search['sn'];
        }
        if ($search['buycount']) {
            $where['buyCount'] = array('GT', $search['buycount']);
        }
        if ($search['buyamount']) {
            $where['cumulativeAmount'] = array('GT', $search['buyamount']);
        }
        if ($search['lastbuytime']) {
            $where['lastBuyTime'] = array('LT', $search['lastbuytime']);
        }
        if ($search['createdTime']) {
            $where['createdTime'] = array(array('LT', $search['createdTime'] . ' 23:59:59'), array('GT', $search['createdTime'] . ' 0:0:0'));
        }
        if ($this->RoleInfo['SEAT']) {
            $where['userID'] = $this->loginData['id'];
        } else if ($this->RoleInfo['ADMIN']) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $where['state'] = 1;
        $tpl = '';
        $table = 'vcustomer';
        switch ($search['tab']) {
            case 'new': // 最近1周
                $where['createdTime'] = array('GT', date('Y-m-d 0:0:0', strtotime('1 week ago')));
                break;
            case 'interested': // 意向客户
                $tpl = 'customer_list_interested_part';
                $where['interested'] = array('GT', 0);
                break;
            case 'appointment_user': // 预约客户
                $table = 'vcustomer_appointment';
                $tpl = 'customer_list_appointment_part';
                $where['source'] = 'USER';
                $where['state'] = 0;
                break;
            case 'appointment_order': // 订单回访
                $table = 'vcustomer_appointment';
                $tpl = 'customer_list_appointment_part';
                $where['source'] = 'ORDER';
                $where['state'] = 0;
                break;
            case 'overdue': // 超期预警(3个月)
                $tpl = 'customer_list_overdue_part';
                $where['lastVisitTime'] = array('LT', date('Y-m-d 0:0:0', strtotime('3 month ago')));
                break;
            case 'dispatch': // 调度客户
                $tpl = 'customer_list_dispatch_part';
                $where['oldUserID'] = array('GT', 0);
                break;
            case 'recycle': // 回收站
                $tpl = 'customer_list_recycle_part';
                $where['state'] = 14;
                break;
        }
        return array('table' => $table, 'search' => $search, 'where' => $where, 'tpl' => $tpl);
    }

    /**
     * customer_list操作
     * @since 1.0.0 <2015-4-2> SoChishun Added.
     */
    public function customer_list() {
        $this->assert_upr(ACTION_NAME); // 检测访问权限
        $this->base_common_add_visit_history('客户管理'); // 添加用户浏览历史
        $search_data = $this->customer_list_search(); // 获取查询表单数据
        $list = D('Customer')->get_paging_list($search_data['where'], $pager);
        $this->assign('list', $list);
        $this->assign('pager', $pager);
        $this->assign('upr', $this->user_permission_rules); // 声明页面权限变量
        $this->display_tpp();
    }

    /**
     * customer_export操作
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function customer_export() {
        $this->checkUPR('导出客户数据');
        $arrSearch = $this->customer_list_search();
        $M = new SoViewModel($arrSearch['table']);
        $list = $M->field("personalName as '客户姓名', telphone as '电话号码', address as '联系地址', serialNo as '客户编号', buyCount as '购买次数', cumulativeAmount as '累计消费', lastBuyTime as '上次购买时间', userName as '工号', createdTime as '创建时间'")->where($arrSearch['where'])->select();
        if (!$list) {
            $this->error('找不到符合条件的记录!');
        }
        sofn_excel_export($list);
    }

    /**
     * customer_edit操作
     * @param int $id 主键编号
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function customer_edit($id = 0) {
        $this->assert_upr(ACTION_NAME); // 检测访问权限
        $this->base_common_add_visit_history($id ? '编辑客户' : '新增客户'); // 添加用户浏览历史
        $this->base_common_edit_view($id, 'Customer');
    }

    /**
     * customer_edit_save操作
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function customer_edit_save() {
        $result = D('Customer')->save_item();
        $this->base_redirect_return($result, U('Customer/customer_list'));
    }

    /**
     * customer_delete操作
     * @param int $id 主键编号
     * @since 1.0 <2015-4-2> SoChishun Added.
     */
    public function customer_delete($id = 0) {
        $this->base_common_delete($id, 'Customer');
    }

    // 客户物理删除 2014-12-25 by sutroon
    public function customer_remove() {
        if (!$this->checkUPR('删除客户', false)) {
            $this->act_ajaxReturn(false, '没有权限!');
        }
        $id = I('id');
        if (!$id) {
            $this->act_ajaxReturn(false, '参数无效!');
        }
        $M = M('tcustomer');
        $siteID = $M->where("id=$id")->getField('siteID');
        $result = $M->delete($id);
        if (false !== $result) {
            M('tcustomer_ex_' . $siteID)->where("userID=$id")->delete();
        }
        $this->act_ajaxReturn($result, '删除%!');
    }

    // 从回收站还原客户 2014-12-25 by sutroon
    public function customer_restore() {
        $id = I('id');
        if (!$id) {
            $this->act_ajaxReturn(false, '参数无效!');
        }
        $result = M('tcustomer')->where("id=$id")->setField('state', 1);
        $this->act_ajaxReturn($result, '还原%!');
    }

    // 导入客户数据表单 2014-12-30 by sutroon
    public function customer_import() {
        $this->display();
    }

    // 导入客户数据 2014-12-30 by sutroon
    public function customer_import_save() {
        $siteID = $this->loginData['siteID'];
        $userID = $this->loginData['id'];
        $skipDuplicate = I('skipDuplicate');
        $rule = I('rule');
        $msg = UploadHandlerAction::uploadToSite($siteID, 'CUSTOMER-IMPORT', array('subFolder' => 'CustomerExcel'), $userID, array('remark' => "$skipDuplicate,$rule"));
        if (!$msg['success']) {
            $this->act_error('导入失败：' . $msg);
        }
        $fid = $msg['data']['fileID'];
        if (!$fid) {
            $this->act_error('文件保存失败!');
        }
        $this->success('文件上传成功,即将处理数据...', U('Customer/customer_import_queue', "i=0&fid=$fid"));
    }

    // 导入客户数据队列检测 2014-12-31 by sutroon
    public function customer_import_queue() {
        $fid = I('fid');
        if (!$fid) {
            die('参数错误!');
        }
        $i = I('i', 0) + 1;
        $tp = create_taskqueue();
        if ($tp->add($id)) {
            $this->customer_import_save_data($fid);
            $tp->delete($id);
            $this->act_close_dialog(true, '导入成功!');
        } else {
            $this->success("系统繁忙,正在努力处理($i)...", U('Customer/customer_import_queue', "i=$i&fid=$fid"));
        }
    }

    // 导入客户数据 保存数据 2014-12-31 by sutroon
    function customer_import_save_data($fid) {
        if (!$fid) {
            die('文件编号不存在!');
        }
        $M = M('tgeneral_file');
        $data = $M->field('fileExt, filePath, remark, siteID, userID')->find($fid);
        if (!$data) {
            die('文件记录不存在');
        }
        if ($data['remark']) {
            $remarks = explode(',', $data['remark']);
            $skipDuplicate = $remarks[0] == '1' ? true : false; // 是否过滤重复数据
            $rule = count($remarks) > 1 ? $remarks[1] : 'order'; // 顺序保存或乱序保存
        }
        $siteID = $data['siteID'];
        $siteID = $data['userID'];
        $arrsql = array();
        $i = 0;
        $n = 0;
        $arrcontent = sofunc_excel_import(UPLOAD_ROOT . $data['filePath']);
        $dir = get_appdata_dir(array('siteID' => $this->loginData['siteID'], 'userID' => $this->loginData['id'], 'type' => 'tempsqls', 'subdir' => 'CustomerImp')) . date('Ymdhis');
        foreach ($arrcontent as $item) {
            if (trim($item) == '') {
                continue;
            }
            $arrsql[] = sprintf("('%s', '%s', '%s', 'IMPORT', %d, %d)", $item['客户姓名'], $item['电话号码'], $item['联系地址'], $userID, $siteID);
            if ($i > 0 && $i % 300 == 0) {
                $sql = 'insert into tcustomer_temp (personalName, telphone, address, exTags, userID, siteID) values ' . implode(',', $arrsql);
                $files[] = $dir . $n . '.sql';
                file_put_contents($dir . $n . '.sql', $sql);
                /**
                  $result = $M->execute($sql);
                  if (false === $result) {
                  die($M->getDbError());
                  } */
                empty($arrsql);
                $n++;
            }
            $i++;
        }
        if ($arrsql) {
            $sql = 'insert into tcustomer_temp (personalName, telphone, address, exTags, userID, siteID) values ' . implode(',', $arrsql);
            $files[] = $dir . $n . '.sql';
            file_put_contents($dir . $n . '.sql', $sql);
            /**
              $result = $M->execute($sql);
              if (false === $result) {
              die($M->getDbError());
              } */
            $n++;
        }
        foreach ($files as $file) {
            $M->execute("load data infile '$file' into table tcustomer_temp");
        }
        sleep(5);
        $M->execute("insert into tcustomer (personalName, telphone, address, exTags, siteID) select personalName, telphone, address, exTags, siteID from tcustomer_temp where siteID=$siteID and userID=$userID");
        $M->execute("delete from tcustomer_temp where siteID=$siteID and userID=$userID");
        $this->act_close_dialog($result, '保存%!');
    }

    // 检测电话号码是否重复 2015-1-2 by sutroon
    public function check_telphone($tel = '') {
        $count = 0;
        if (C('APPCONF.CUSTOMER_EDIT_TELPHONE_CHECK')) {
            $siteID = $this->loginData['siteID'];
            if ($tel) {
                $tel = ltrim($tel, '0');
                $count = M('tcustomer')->where("telphone='$tel' and siteID=$siteID")->count();
            }
        }
        $this->ajaxReturn(array('success' => $count < 1));
    }

    // 预约回访 2014-12-24 by sutroon
    public function appointment_edit() {
        $this->checkUPR('预约客户');
        $id = I('id');
        $customerID = I('customerID');
        if (!$customerID) {
            $this->act_close_dialog(false, '参数有误!', '', false);
        }

        $data = M('tcustomer')->field('id as customerID, personalName, serialNo, siteID')->find($customerID);
        if (!$data) {
            $this->act_close_dialog(false, '客户不存在!', '', false);
        }
        $M = M('tcustomer_appointment');
        if ($id) {
            $data2 = $M->find($id);
            $data = array_merge($data, $data2);
        }
        $list = $M->where("customerID=$customerID")->select();
        $this->assign('data', $data);
        $this->assign('list', $list);
        $this->assign('UPR', $this->UPR);
        $this->display();
    }

    // 预约回访数据保存 2014-12-24 by sutroon
    public function appointment_edit_save() {
        $this->checkUPR('预约客户');
        $id = I('id');
        $customerID = I('customerID');
        $params = create_params();
        $params->addParam('siteID', 'number', '租户ID无效!');
        $params->addParam('customerID', 'number', '客户无效!');
        $params->addParam('time', 'require', '预约时间无效!');
        if ($id) {
            $params->addParam('state', 'number', '回访状态未选择');
        }
        if ($params->hasError()) {
            $this->act_error($params->getError());
        }
        $params->addData('remark');
        $params->addData('result');
        $params->addData('source', 'USER');
        $params->addData('updatedTime');
        $M = M('tcustomer_appointment');
        if ($id) {
            $params->addData('id', $id);
            $result = $M->save($params->getParams());
        } else {
            $result = $M->add($params->getParams());
        }
        $this->act_close_dialog($result, '保存%!');
    }

    // 客户调度记录 2014-12-25 by sutroon
    public function dispatch_log_list() {
        $customerID = I('customerID');
        if (!$customerID) {
            $this->act_close_dialog(false, '参数有误!');
        }
        $list = M('vcustomer_dispatch')->where("customerID=$customerID")->select();
        $this->assign('list', $list);
        $this->display2();
    }

    // 获取客户调度查询表单数据 2014-12-25 by sutroon
    function dispatch_edit_get_search() {
        $search['lastBuyTimeExpBegin'] = I('lastBuyTimeExpBegin');
        $search['lastBuyTimeBegin'] = I('lastBuyTimeBegin');
        $search['lastBuyTimeExpEnd'] = I('lastBuyTimeExpEnd');
        $search['lastBuyTimeEnd'] = I('lastBuyTimeEnd');
        $search['lastVisitTimeExpBegin'] = I('lastVisitTimeExpBegin');
        $search['lastVisitTimeBegin'] = I('lastVisitTimeBegin');
        $search['lastVisitTimeExpEnd'] = I('lastVisitTimeExpEnd');
        $search['lastVisitTimeEnd'] = I('lastVisitTimeEnd');
        $search['buyCountExp'] = I('buyCountExp');
        $search['buyCount'] = I('buyCount');
        $search['cumulativeAmountExp'] = I('cumulativeAmountExp');
        $search['cumulativeAmount'] = I('cumulativeAmount');
        $search['oldUsers'] = I('oldUsers');
        $search['buyCountState'] = I('buyCountState');
        $search['searchNumber'] = I('searchNumber');
        if ($search['lastBuyTimeExpBegin'] && $search['lastBuyTimeBegin']) {
            $where['lastBuyTime'] = array($search['lastBuyTimeExpBegin'], $search['lastBuyTimeBegin']);
        }
        if ($search['lastBuyTimeExpEnd'] && $search['lastBuyTimeEnd']) {
            if (isset($where['lastBuyTime'])) {
                $where['lastBuyTime'] = array($where['lastBuyTime'], array($search['lastBuyTimeExpEnd'], $search['lastBuyTimeEnd']));
            } else {
                $where['lastBuyTime'] = array($search['lastBuyTimeExpEnd'], $search['lastBuyTimeEnd']);
            }
        }

        if ($search['lastVisitTimeExpBegin'] && $search['lastVisitTimeBegin']) {
            $where['lastVisitTime'] = array($search['lastVisitTimeExpBegin'], $search['lastVisitTimeBegin']);
        }
        if ($search['lastVisitTimeExpEnd'] && $search['lastVisitTimeEnd']) {
            if (isset($where['lastVisitTime'])) {
                $where['lastVisitTime'] = array($where['lastVisitTime'], array($search['lastVisitTimeExpEnd'], $search['lastVisitTimeEnd']));
            } else {
                $where['lastVisitTime'] = array($search['lastVisitTimeExpEnd'], $search['lastVisitTimeEnd']);
            }
        }
        if ($search['buyCount'] && $search['buyCountExp']) {
            $where['buyCount'] = array($search['buyCountExp'], $search['buyCount']);
        }
        if (strlen($search['buyCountState']) > 0) {
            switch ($search['buyCountState']) {
                case '1':
                    $where['buyCount'] = array('GT', 0);
                    break;
                case '0':
                    $where['buyCount'] = array('EQ', 0);
                    break;
                case '2':
                    if ($where['buyCount']) {
                        unset($where['buyCount']);
                    }
                    break;
            }
        }
        if ($search['cumulativeAmount'] && $search['cumulativeAmountExp']) {
            $where['cumulativeAmount'] = array($search['cumulativeAmountExp'], $search['cumulativeAmount']);
        }
        if ($search['oldUsers']) {
            $search['oldUsers'] = str_replace("'", '', $search['oldUsers']);
            $search['oldUsers'] = str_replace(' ', '', $search['oldUsers']);
            $search['oldUsers'] = str_replace(",", "','", $search['oldUsers']);
            $uids = M('tuser')->where("userType='SEAT' and userName in ('" . $search['oldUsers'] . "')")->getField('id', true);
            if ($uids) {
                $where['userID'] = array('IN', $uids);
            }
        }
        return array('search' => $search, 'where' => $where);
    }

    // 客户调度 2014-12-25 by sutroon
    public function dispatch_edit() {
        $this->checkUPR('调度客户');
        $customerID = I('customerID');
        if ($customerID) {
            $search = false;
            $where['id'] = $customerID;
        } else {
            $arr = $this->dispatch_edit_get_search();
            $search = $arr['search'];
            $where = $arr['where'];
        }
        $count = 0;
        $hasOrderCount = 0;
        if ($where) {
            if ($this->RoleInfo['SEAT']) {
                $where['userID'] = $this->loginData['id'];
            } else if ($this->RoleInfo['ADMIN']) {
                $where['siteID'] = $this->loginData['siteID'];
            }
            $M = M('tcustomer');
            if ($search['searchNumber']) {
                $M->limit($search['searchNumber']);
            }
            $list = $M->where($where)->field('id, personalName, buyCount, userID')->select();
            if ($list) {
                $count = count($list);
                foreach ($list as $row) {
                    if ($row['buyCount'] > 0) {
                        $hasOrderCount++;
                    }
                }
            }
        }
        $this->assign('count', $count);
        $this->assign('hasOrderCount', $hasOrderCount);
        $this->assign('list', $list);
        $this->assign('search', $search);
        $this->assign('UPR', $this->UPR);
        $this->display();
    }

    // 客户调度数据保存 2014-12-25 by sutroon
    public function dispatch_edit_save() {
        $this->checkUPR('调度客户');
        $ids = I('ids');
        if (!$ids) {
            $this->act_error('未选择客户!');
        }
        $newUsers = I('newUsers');
        if ($newUsers) {
            $newUsers = str_replace("'", '', $newUsers);
            $newUsers = str_replace(' ', '', $newUsers);
            $newUsers = str_replace(',', "','", $newUsers);
        }
        if (!$newUsers) {
            $this->act_error('新工号未填写');
        }
        $siteID = $this->loginData['siteID'];
        $M = M('tuser');
        $arrUsers = $M->where("userName in ('$newUsers') and userType='SEAT'")->getField('id', true);
        if (!$arrUsers) {
            $this->act_error("新工号['$newUsers']不是有效座席!");
        }
        $perNumber = I('perNumber');
        if (!$perNumber || !is_numeric($perNumber) || $perNumber < 1) {
            $perNumber = ceil(count($ids) / count($arrUsers));
        }
        $remark = I('remark');
        $adminID = $this->loginData['id'];
        $name = date('Ymd-his-') . $adminID;
        $i = 0;
        $n = 0;
        $sql = "insert into tcustomer_dispatch (`name`, customerID, oldUserID, userID, adminID, remark, siteID) values";
        $sqls = false;
        foreach ($ids as $ele) {
            $arrEle = explode('/', $ele);
            $userID = $arrUsers[$n];
            $sqls[] = "('$name', " . $arrEle[0] . ", " . $arrEle[1] . ", $userID, $adminID, '$remark', $siteID)";
            if ($i % $perNumber == 0) {
                $n++;
            }
            $i++;
            if ($i > 0 && ($i % 300 == 0)) {
                $sqltemp = $sql . implode(',', $sqls);
                // echo '<br />' . $sqltemp;
                $result = $M->execute($sqltemp);
                if (false === $result) {
                    die($M->getDbError());
                }
                empty($sqls);
                sleep(2);
            }
        }
        if ($sqls) {
            $sqltemp = $sql . implode(',', $sqls);
            // echo '<br />' . $sqltemp;
            $result = $M->execute($sqltemp);
            if (false === $result) {
                die($M->getDbError());
            }
        }
        $result = mysql_query("call proc_customer_dispatch('$name',@result)");
        if (false === $result) {
            die(mysql_error());
        }
        $result = mysql_query('select @result');
        $arrCode = mysql_fetch_array($result);
        if (false === $arrCode) {
            die(mysql_error());
        }
        $this->act_close_dialog($arrCode['@result'] == '1', sofunc_get_procedure_result_text($arrCode['@result']));
    }

}
